import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
let service = null
window._axiosPromiseArr = []
service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000 // request timeout
})
// 添加请求拦截器
service.interceptors.request.use((config) => {
  // console.log(config)
  config.cancelToken = new axios.CancelToken(cancel => {
    window._axiosPromiseArr.push({ cancel })
  })
  let token = window.sessionStorage.getItem('token')
  if (token) {
    // 将token放到请求头发送给服务器,将tokenkey放在请求头中
    config.headers['X-Access-Token'] = token
    return config
  }
  return config
}, (error) => {
  return Promise.resolve(error)
})
// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log('response')
    console.log(response)
    if (response.status === 200) {
      return response
    } else {
      // message.error(response)
      return Promise.reject(response)
    }
  },
  (error) => {
    console.log(error.response)
    if (error.response.status === 500) {
      Message.error({
        message: 'token失效',
        onClose: function () { }
      })
      window.sessionStorage.clear()
      window.location.href = '/'
    }
    return Promise.reject(error)
  }
)

// 返回axios请求实例
const request = (params) => {
  return new Promise((resolve, reject) => {
    service(params)
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export default request
